$(function(){
	
	$("#searchlink").click(function(event){
		event.preventDefault();
		var time = getTime();
		
		$("#searchresult").children().remove();
		
		$("<div />").attr({id: "timesearch", class: "searchbox"}).appendTo("#searchresult");
		$("<form />").attr({id: "advsearch", method: "post", action:"index.php", autocomplete:"off"}).appendTo("#timesearch");
		$("<label />").attr({for: "start", id: "startlbl", class: "relative"}).text("Start").appendTo("#advsearch");
		$("<input />").attr({name: "start", id: "start", type: "text", class: "inputstyle station", value: "Stationnamn"}).keyup(keyup).focus(fcs).blur(blr).appendTo("#startlbl");
		$("<label />").attr({for: "starttime", id: "starttimelbl"}).text("Tid").appendTo("#advsearch");
		$("<input />").attr({name: "starttime", id: "starttime", type: "text", class: "inputstyle inputtime", value: time}).focus(fcs).blur(blr).appendTo("#starttimelbl");
		$("<label />").attr({for: "destination", id: "destinationlbl", class: "relative"}).text("Mål").appendTo("#advsearch");
		$("<input />").attr({name: "destination", id: "destination", type: "text", class: "inputstyle station", value: "Stationnamn"}).keyup(keyup).focus(fcs).blur(blr).appendTo("#destinationlbl");
		$("<label />").attr({for: "stoptime", id: "stoptimelbl"}).text("Tid").appendTo("#advsearch");
		$("<input />").attr({name: "stoptime", id: "stoptime", type: "text", class: "inputstyle inputtime", value: time}).focus(fcs).blur(blr).appendTo("#stoptimelbl");
		$("<input />").attr({type: "submit", value: "Sök", id: "advsubmit", name: "advsubmit"}).appendTo("#advsearch");
		
		$("<div />").attr({id: "stationsearch", class: "searchbox"}).appendTo("#searchresult");
		$("<form />").attr({id: "advstationsearch", method: "post", action:"index.php", autocomplete:"off"}).appendTo("#stationsearch");
		$("<label />").attr({for: "station", id: "stationlbl", class: "relative"}).text("Station").appendTo("#advstationsearch");
		$("<input />").attr({name: "station", id: "station", type: "text", class: "inputstyle station", value: "Stationnamn"}).keyup(keyup).focus(fcs).blur(blr).appendTo("#stationlbl");
		$("<input />").attr({type: "submit", value: "Sök", id: "advstationsubmit", name: "advstationsubmit"}).click(advsubmit).appendTo("#advstationsearch");
		
		$("<div />").attr({id: "endsearch", class: "searchbox"}).appendTo("#searchresult");
	});
	
	var active = "";
	function keyup(event){			//function för Autocomplete
		var nr = 0;
		$(".autocomp").remove();
		var value = $(this).val();
		active = $(this);
		$("<div />").attr({class: "autocomp"}).appendTo($(this).parent());
		for(var i=0; i<autocomplete.length; i++){
			if (autocomplete[i].match(value)){
				$("<p />").text(autocomplete[i]).attr({class: "autoparagraf"}).click(autoclick).appendTo(".autocomp");
				nr++;
			}
		}
		if(nr == 0){
			$(".autocomp").remove();
		}
	}

	var bound1;
	var bound2;
	var bound3;
	var bound4;
	var done = "";
	var numberresult = "";
	//var map = "";
	$("#numsubmit").click(function(event){
		event.preventDefault();
		$("#searchresult").children().remove();
		$("#numberresult").remove();
		$("#errormsg").remove();
		var trainnumber = $("#numinput").val();
		$.post("php/getinfo.php", { info: "trains", data: trainnumber },
			function(data) {
				data = $.parseJSON(data);
				if(data[0]['result'] == 0){
					$("<span />").attr({id: "errormsg"}).text("Kan inte hitta tåget du söker efter").appendTo("#search");
				}else{
					for(var i=1; i<data.length; i++){
						
						var starttime;
						var endtime;
						var time = getTime();
						if(data[i]['newdeparture'] && i > 1){
							var done = compareTime(data[i]['newdeparture'],time, 2);
							if(done > 0){
								var paststation = data[i-1]['station'];
								var upcommingstation = data[i]['station'];
								initialize();
						//		creategdir();
						//		setDirections(paststation, upcommingstation);
								if(data[i-1]['newdeparture']){
									starttime = data[i-1]['newdeparture'];
								}else if(data[i-1]['ordinarydeparture']){
									starttime = data[i-1]['ordinarydeparture']
								}
								if(data[i]['newarrival']){
									endtime = data[i]['newarrival'];
								}else if(data[i]['ordinaryarrival']){
									endtime = data[i]['ordinaryarrival'];
								}
								
								$.post("php/getinfo.php", {info : 'location', data : paststation.replace(" ","%20")+",+station,+sweden", data2 : upcommingstation.replace(" ","%20")+",+station,+sweden"}, function(data){
									data = $.parseJSON(data);
									
									drawPoint(data[0].lat,data[0].lang, paststation);
									drawPoint(data[1].lat,data[1].lang, upcommingstation);
									if (data[0].lat < data[1].lat){
										bound1 = data[1].lat;
										bound3 = data[0].lat;
									} else {
										bound1 = data[0].lat;
										bound3 = data[1].lat;
									}
									if (data[0].lang < data[1].lang){
										bound2 = data[1].lang;
										bound4 = data[0].lang;
									} else {
										bound2 = data[0].lang;
										bound4 = data[1].lang;
									}
									
									setBoundEast(bound1,bound2);
									setBoundWest(bound3,bound4);
									fitBounds();

									var line = [
										new google.maps.LatLng(data[0].lat, data[0].lang),
										new google.maps.LatLng(data[1].lat, data[1].lang),
									];

									var draw = new google.maps.Polyline({
										path: line,
										strokeColor: "#FF0000",
										strokeOpacity: 1.0,
										strokeWeight: 2
									});

									draw.setMap(map);
								});
								
								break;
							}
						}else if(!data[i]['newdeparture']){
							if(data[i]['newarrival']){
								var done = compareTime(data[i]['newarrival'],time, 2);
								if(done < 0){
									var station = data[i]['station'];
									
									$.post("php/getinfo.php", {info : 'location', data : station.replace(" ","%20")+",+station,+sweden", data2 : station.replace(" ","%20")+",+station,+sweden"}, function(data){
										data = $.parseJSON(data);
										initializeelse(data[0].lat,data[0].lang);
										drawPoint(data[0].lat,data[0].lang, station);
									});
									
									break;
								}
							}
						}/*else if(compareTime(data[1]['newdeparture'],time, 2) > 0){
								var station = data[i]['station'];
								
								$.post("php/getinfo.php", {info : 'location', data : station.replace(" ","%20")+",+station,+sweden", data2 : station.replace(" ","%20")+",+station,+sweden"}, function(data){
									data = $.parseJSON(data);
									initializeelse(data[0].lat,data[0].lang);
									drawPoint(data[0].lat,data[0].lang, station);
								});
								
								break;
						}*/
					}
					
					
					numberresult = $("<div />").attr({id: "numberresult", class: "result"}).appendTo("#main");
					var topbar = $("<div />").attr({id: "topbar", class: "bar"}).appendTo(numberresult);
					var color = "red";
					$("<span />").text("Ankomst").appendTo(topbar);
					$("<span />").text("Avgång").appendTo(topbar);
					$("<span />").text("Station").appendTo(topbar);
					for(var i=1; i<data.length; i++){
						var rowbar = $("<div />").attr({id: "rowbar", class: "bar"}).appendTo(numberresult);
						if(data[i]['newarrival']){
							if(data[i]['ordinaryarrival']){
								var done = compareTime(data[i]['newarrival'],data[i]['ordinaryarrival'], 1);
								if(done == 0){
									color = "black";
									done = "";
								}else if(done < 0){
									color = "green";
									done = "("+done+")";
								}else{
									done = "("+done+")";
								}
							}
							$("<span />").text(data[i]['newarrival'] +done).css({color:color}).appendTo(rowbar);
							color = "red";
						}else if(data[i]['ordinaryarrival']){
							$("<span />").text(data[i]['ordinaryarrival']).appendTo(rowbar);
						}else{
							$("<span />").text("-").appendTo(rowbar);
						}
						if(data[i]['newdeparture']){
							if(data[i]['ordinarydeparture']){
								done = compareTime(data[i]['newdeparture'],data[i]['ordinarydeparture'], 1);
								if(done == 0){
									color = "black";
									done = "";
								}else{
									done = "("+done+")";
								}
							}
							$("<span />").text(data[i]['newdeparture'] +done).css({color:color}).appendTo(rowbar);
							color = "red";
						}else if(data[i]['ordinarydeparture']){
							$("<span />").text(data[i]['ordinarydeparture']).appendTo(rowbar);
						}else{
							$("<span />").text("-").appendTo(rowbar);
						}
						if(data[i]['station']){
							$("<span />").text(data[i]['station']).appendTo(rowbar);
						}
					}
				}
			}
		);
	});
	
	function advsubmit(event){		//func för avancerad sökning
		event.preventDefault();
		var stationname = $("#station").val();
		$("#searchresult").children().remove();
		$.post("php/getinfo.php", { info: "stations", data: stationname },	//info vad vi hämtar, data vilken station
			function(data) {
				
				data = $.parseJSON(data);
				
				var advresult = $("<div />").attr({id: "advresult", class: "result"}).appendTo("#searchresult");
				var topbar = $("<div />").attr({id: "topbar", class: "bar"}).appendTo(advresult);
				$("<span />").text("Tid").appendTo(topbar);
				$("<span />").text("Information").appendTo(topbar);
				$("<span />").text("Spår").appendTo(topbar);
				for(var i=0; i<data.length; i++){
					var rowbar = $("<div />").attr({id: "rowbar", class: "bar"}).appendTo("#advresult");
					$("<span />").text(data[i]['tid']).appendTo(rowbar);
					$("<span />").text("something").appendTo(rowbar);
					$("<span />").text("nothing").appendTo(rowbar);
				}
			}
		);
	}
	
	function autoclick(event){		//function för att klicka i autocomplete rutan
		active.val($(this).text());
		$(".autocomp").remove();
	}
	
	$("body").click(function(event){	//func för att ta bort autocomplete rutan
		if(event.target = $("input")){
			$(".autocomp").remove();
		}
	});	
	
	var text = "";
	$("input").focus(fcs);
	function fcs(){					//func för att välja en input
		if($(this).hasClass("inputstyle")){
			text = $(this).val();
			$(this).val("");
			$(this).removeClass("inputstyle");
		}
	}
	
	$("input").blur(blr);
	function blr(){					//func för att avmarkera en input
		if($(this).val() == ""){
			$(this).val(text);
			$(this).addClass("inputstyle");
		}
	}
	
/*	function fcstime(){
		if($(this).hasClass("inputstyle")){
			text = $(this).val();
			$(this).val("");
			$(this).removeClass("inputstyle");
		}
		$(".clockhour").remove();
		$(".clockmin").remove();
		var value = $(this).val();
		active = $(this);
		$("<div />").attr({class: "clockcomp"}).appendTo($(this).parent());
		for(var i=0; i<autocomplete.length; i++){
			if (autocomplete[i].match(value)){
				$("<p />").text(autocomplete[i]).attr({class: "autoparagraf"}).click(autoclick).appendTo(".autocomp");
				nr++;
			}
		}
		if(nr == 0){
			$(".autocomp").remove();
		}
	}
	
	function clockclick(event){		//function för att klicka i autocomplete rutan
		active.val($(this).text());
		$(".clockcomp").remove();
	}*/
	
	
});

function compareTime(time1, time2, flag) {
	var hou1  = time1.substring(0,2);
	if(hou1 == 00){
		hou1 = "24";
	}
	var min1 = time1.substring(3,5);
	
	var hou2  = time2.substring(0,2);
	if(hou2 == 00){
		hou2 = "24";
	}
	var min2 = time2.substring(3,5);
	
	result1 = hou1 - hou2;
	result2 = min1 - min2;
	if (result1 == 1){
		result2 = result2+60;
	}
	if (result1 == -1){
		result2 = result2-60;
	}
	
	if (flag == 2 && (result1 < 1 && result2 < 1)){
		return result2;
	}
	
	return result2;
}

function getTime(){
	var time = new Date();
	var hours = time.getHours()
	if (hours < 10){
		hours = "0"+hours;
	}
	var minutes = time.getMinutes()
	if (minutes < 10){
		minutes = "0"+minutes;
	}
	time = hours+":"+minutes;
	
	return time;
}

var southWest;
var northEast;
var map;
var overlay;
function initialize() {
	var myLatLng = new google.maps.LatLng(-27.46758, 153.027892);
	var myOptions = {
		zoom: 5,
		center: myLatLng,
		streetViewControl: false,
		draggable: false,
		zoomControl: false,
		scrollwheel: false,
		panControl: false,
		mapTypeControl: false,
		disableDoubleClickZoom: false,
		keyboardShortcuts: false,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};

	map = new google.maps.Map($("#searchresult")[0],
		myOptions);
		
}
/*
function createoverlay(){

	var swBound = new google.maps.LatLng(62.281819, -150.287132);
	var neBound = new google.maps.LatLng(62.400471, -150.005608);
	var bounds = new google.maps.LatLngBounds(swBound, neBound);

	var srcImage = 'train-icon.gif';
	overlay = new USGSOverlay(bounds, srcImage);
}
*/
function initializeelse(lat,lang) {
	var myLatLng = new google.maps.LatLng(lat,lang);
	var myOptions = {
		zoom: 13,
		center: myLatLng,
		streetViewControl: false,
		draggable: false,
		zoomControl: false,
		scrollwheel: false,
		panControl: false,
		mapTypeControl: false,
		disableDoubleClickZoom: false,
		keyboardShortcuts: false,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};

	map = new google.maps.Map($("#searchresult")[0],
		myOptions);
}
/*
function USGSOverlay(bounds, image) {

	this.bounds_ = bounds;
	this.image_ = image;
	this.map_ = map;

	this.div_ = null;

	this.setMap(map);
}

USGSOverlay.prototype = new google.maps.OverlayView();

USGSOverlay.prototype.onAdd = function() {

  var div = document.createElement('DIV');
  div.style.border = "none";
  div.style.borderWidth = "0px";
  div.style.position = "absolute";

  var img = document.createElement("img");
  img.src = this.image_;
  img.style.width = "100%";
  img.style.height = "100%";
  div.appendChild(img);

  this.div_ = div;

  var panes = this.getPanes();
  panes.overlayLayer.appendChild(div);
}

USGSOverlay.prototype.draw = function() {

  var overlayProjection = this.getProjection();

  var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
  var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());

  var div = this.div_;
  div.style.left = sw.x + 'px';
  div.style.top = ne.y + 'px';
  div.style.width = (ne.x - sw.x) + 'px';
  div.style.height = (sw.y - ne.y) + 'px';
}
*/
function fitBounds(){
	var bounds = new google.maps.LatLngBounds(southWest,northEast);
	map.fitBounds(bounds);
}

function setBoundWest(lat, lang){
	southWest = new google.maps.LatLng(lat,lang);
}

function setBoundEast(lat, lang){
	northEast = new google.maps.LatLng(lat,lang);
}

function drawPoint(lat, lang, title){
	var image = "train-icon.gif";
    var marker = new google.maps.Marker({
	position: new google.maps.LatLng(lat, lang),
	title: title,
	map: map,
	icon: image
    });
}

var autocomplete = ["Abisko turiststation","Abisko Östra","Alingsås","Alvesta","Aneby","Anneberg","Arboga","Arbrå","Arlanda C","Arvika","Avesta centrum" ,"Avesta Krylbo",
					"Bankeryd","Bastuträsk","Berga","Billeberga","Bjuv","Björbo","Björkliden","Blomstermåla","Bodafors","Boden C","Bollebygd","Bollnäs","Bor","Borlänge C","Borås C","Boxholm","Bromölla","Brunflo","Bräcke","Bräkne-Hoby","Burlöv","Bålsta","Båstad",
					"Charlottenberg",
					"Dala-Floda","Dala-Järna","Degerfors","Dingtuna","Djurås","Duved","Dösjebro","Ed","Edane","Eksjö","Emmaboda","Enafors","Enköping","Erikslund","Eskilstuna C","Eslöv","Fagersta C",
					"Fagersta Norra","Fagerås","Falkenberg","Falköping C","Falun C","Fjällåsen","Flemingsberg","Flen","Floby","Fors","Forserum","Fränsta","Frövi","Furuvik",
					"Gagnef","Gantofta","Glumslöv" ,"Gnarp","Gnesta","Gnosjö","Grums","Grängesberg","Grästorp","Gunnesbo","Gårdsjö","Gällivare","Gällö","Gävle C","Göteborg C",
					"Habo","Hallsberg","Hallstahammar","Halmstad C","Heby","Hedemora","Helsingborg C","Herrljunga","Hestra","Hindås","Hjältevad","Hjärup","Hofors","Holmsjö","Holmsveden","Horndals Bruk","Hovmantorp","Hudiksvall","Hultsfred","Huskvarna","Husum","Hyllie","Håkantorp","Häljarp","Hälleforsnäs","Hällnäs","Härnösand","Hässleholm","Högboda","Högsby","Hörnefors","Höör",
					"Iggesund","Insjön",
					"Järpen","Järvsö","Jönköping C","Jörn",
					"Kalmar C","Karbenning","Karlshamn","Karlskrona C","Karlstad C","Katrineholm C","Kattarp","Katterjåkk","Kil","Kilafors","Kimstad","Kiruna C","Kisa","Klevshult","Klippan","Knivsta","Kode","Kolbäck","Kolmården","Kopparberg","Kristianstad C","Kristinehamn","Krokom","Kumla","Kungsbacka","Kungsbacka Hede","Kungsör","Kvicksund","Kållered","Kävlinge","Köping",
					"Laholm","Landeryd","Landskrona","Laxå","Leksand","Lessebo","Lidköping","Limmared","Lindesberg","Lindome","Lingbo","Linghem","Linköping C","Liseberg","Ljungaverk","Ljungskile","Ljusdal","Ljusne","Ludvika","Luleå C","Lund C","Låktatjåkka","Långsele","Läggesta",
					"Malmbäck","Malmö C","Malung","Malung Folkhögskola","Malung Gymnasium","Mantorp","Maria","Mariannelund","Markaryd","Mehedeby","Mellansel","Mellerud","Mjölby","Mockfjärd","Mora","Morgongåva","Motala C","Mullsjö","Murjek","Månsarp","Märsta","Mölndal","Mölnlycke","Mörarp","Mörrum",
					"Nordmaling","Norrköping C","Nybro","Nykvarn","Nyköping C","Nås","Nässjö C",
					"Ockelbo","Osby","Oxie",
					"Persborg","Perstorp","Pilgrimstad","Påarp",
					"Ramlösa","Ramnäs","Ransta","Riksgränsen","Rimforsa","Ronneby","Rydaholm","Rydebäck","Rydsgård","Rågsveden","Rättvik","Rävlanda","Rörstorp",
					"Sala","Sandared","Sandhem","Sandviken","Skillingaryd","Skinnskatteberg","Skurup","Skutskär","Skyttorp","Skövde C","Smedjebacken","Smålandsstenar","Stavre","Stehag","Stenstorp","Stenungsund","Stockaryd","Stockholm C","Stora Höga","Storlien","Storvik","Storvreta","Storå","Strängnäs","Stångby","Ställdalen","Stöde","Sundbyberg","Sunderby sjukhus","Sundsvall C","Sundsvall Västra","Surahammar","Svarte","Svedala","Svenshögen","Svågertorp / Malmö Syd" ,"Säffle","Säter","Sävsjö","Söderbärke","Söderhamn","Södertälje Syd","Sölvesborg",
					"Taberg","Teckomatorp","Tenhult","Tierp" ,"Tillberga","Timrå","Tobo","Tomelilla","Torpshammar","Torsåker","Torup","Tranås","Triangeln","Trollhättan C","Tyringe","Tågarp","Tällberg","Töreboda",
					"Uddevalla C","Uddevalla Östra","Umeå C","Umeå Östra","Undersåker","Upplands Väsby","Uppsala C",
					"Vad","Vaggeryd","Vagnhärad","Vallsta","Vallåkra","Vansbro","Vara","Varberg","Vargön","Vattholma","Vedum","Vetlanda","Vikingstad","Vimmerby","Vindeln","Vingåker","Vinslöv","Virsbo","Vårgårda","Välsviken","Vänersborg C","Vännäs","Värnamo","Väse","Västervik","Västerås C","Växjö",
					"Ystad","Ytterby","Yttermalung",
					"Åkarp","Åmotfors","Åmål","Ånge","Ånn","Åre","Åstorp","Åtvidaberg",
					"Älmhult","Älvkarleby","Älvsbyn","Älvsjö","Älvängen","Äng","Ängelholm","Ängelsberg","Äppelbo",
					"Ödåkra","Örbyhus","Örebro C","Örebro Södra","Örnsköldsvik C","Örnsköldsvik Norra","Örtofta","Östersund C","Östersund Västra","Öxnered"];